package com.sun.umbrella.service.shiro.realm;

import com.sun.umbrella.dao.OauthUserMapper;
import com.sun.umbrella.domain.entity.OauthUserDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * @author Jay
 * @version v1.0
 * @description 用户realm
 * @date 2017-11-18 23:00
 */

@Slf4j
public class UserRealm extends AuthorizingRealm {


    @Autowired
    private OauthUserMapper oauthUserMapper;


    private static final String ADMIN = "admin";

    /**
     * 登录验证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String userName = usernamePasswordToken.getUsername();
        if (StringUtils.isEmpty(userName)) {
            throw new UnknownAccountException("账号不能为空");
        }
        OauthUserDO oauthUserDO = oauthUserMapper.selectByUserName(userName);
        if (oauthUserDO == null) {
            throw new UnknownAccountException("账号不存在");
        }
        return new SimpleAuthenticationInfo(userName, oauthUserDO.getPassword(), ByteSource.Util.bytes(userName), getName());
    }


    /**
     * 授权会被shiro回调的方法
     * <p>
     * 1.从PrincipalCollection获取登录信息
     * 2.利用登录的用户信息来获取当前用户的角色或权限(可能需要查询数据库)
     * 3.创建SimpleAuthorizationInfo对象,并设置其属性rules属性
     * 4.返回SimpleAuthorizationInfo对象
     * </p>
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("当前授权用户为: {}", principalCollection);
        String userName = (String) principalCollection.getPrimaryPrincipal();

        Set<String> roles = new HashSet<>();
        roles.add("user");
        if (!StringUtils.isEmpty(userName) && userName.endsWith(ADMIN)) {
            roles.add("admin");
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(roles);
///        authorizationInfo.setRoles(userService.findRoles(userName));
///        authorizationInfo.setStringPermissions(userService.findPermissions(username));
        return authorizationInfo;
    }
}
